﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;

namespace Frame.Lib.Utilities
{
    
    public class NetworkAdapter
    {
        public NetworkAdapter() { }

        #region 获得网卡的第一个物理地址
        /// <summary>
        /// 获得网卡的第一个物理地址
        /// </summary>
        /// <returns></returns>
        public static string GetFirstMacAddr()
        {
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();

            string strMac = "";
            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"] == true)
                {
                    strMac = mo["MacAddress"].ToString();
                    mo.Dispose();
                    break;
                }
                mo.Dispose();
            }
            if (strMac == "")
            {
                strMac = "00:00:00:00:00:00";
                //throw new Exception("没有网卡或被禁用");
            }
            return strMac;
        }
        #endregion

        #region 获得所有网卡的物理地址
        /// <summary>
        /// 获得所有网卡的物理地址
        /// </summary>
        /// <returns></returns>
        public static List<string> GetAllMacAddr()
        {
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();

            List<string> macs = new List<string>(5);

            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"] == true)
                {
                    macs.Add(mo["MacAddress"].ToString());
                }
                mo.Dispose();
            }
            //if (macs.Count == 0)
            //{
            //    throw new Exception("没有网卡或被禁用");
            //}
            return macs;
        }
        #endregion
    }
}
